<template>
  <div class="tag-factory devired-logic">
    <factory-config-list ref="factoryConfigList" @addItem="addItem" @clearConfig="clearConfig"></factory-config-list>
    <div class="factory-content" v-loading="loading">
      <el-form :model="editForm" ref="editForm" label-width="0">
        <el-row :gutter="20">
          <el-col :span="6" align="left">
            <div class="factory-top">
              <h2>
                <icon-svg name="iconRole" slot="prefix"></icon-svg>
                逻辑分群
              </h2>
            </div>
          </el-col>
          <el-col :span="18" align="right">
            <div class="btns">
              <el-button @click="clear">
                <icon-svg name="iconCancel"></icon-svg>
                取消
              </el-button>
              <el-button type="primary" @click="handlePreview">
                <icon-svg name="iconFacEye"></icon-svg>
                预览
              </el-button>
              <el-button type="primary" @click="submit">
                <icon-svg name="iconSave"></icon-svg>
                保存
              </el-button>
            </div>
          </el-col>
        </el-row>
        <div class="factory-content-wrapper tag-scrollbar">
          <!-- 逻辑组合 -->
          <div class="section-title">
            <i :class="showLogic ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" @click="showLogic = !showLogic"></i>
            组合逻辑
            <span>已添加{{ editForm.configJson.length }}个枚举值</span>
          </div>
          <el-collapse-transition>
            <div class="section-wrappper" v-if="showLogic">
              <div class="default-enum">
                <el-form-item
                  prop="defaultEnum"
                  label="空值对应的枚举值别称: "
                  label-width="200px"
                  :rules="[
                    {
                      required: true,
                      message: '枚举值别称不能为空',
                      trigger: 'blur'
                    }
                  ]"
                >
                  <el-input
                    v-model="editForm.defaultEnum"
                    placeholder="请输入空值对应的枚举值别称"
                    prefix-icon="el-icon-edit"
                  ></el-input>
                </el-form-item>
              </div>
              <template v-if="editForm.configJson.length">
                <el-tabs type="border-card" v-model="activeEnum">
                  <el-tab-pane
                    :key="index"
                    v-for="(item, index) in editForm.configJson"
                    :label="item.enum || '新增枚举值'"
                    :name="'enum' + index"
                  >
                    <logic-content :derivedTagData="item" :formProp="`configJson.${index}`">
                      <template #btnGroup>
                        <div class="logic-handler">
                          <el-tooltip effect="dark" content="添加枚举值" placement="top" :enterable="false">
                            <el-button
                              type="primary"
                              size="mini"
                              icon="el-icon-plus"
                              circle
                              @click="addGroup(index)"
                            ></el-button>
                          </el-tooltip>
                          <el-tooltip effect="dark" content="删除枚举值" placement="top" :enterable="false">
                            <el-button
                              type="danger"
                              size="mini"
                              icon="el-icon-delete"
                              circle
                              @click="deleteGroup(index)"
                            ></el-button>
                          </el-tooltip>
                          <el-tooltip effect="dark" content="上移" placement="top" :enterable="false">
                            <el-button
                              type="primary"
                              size="mini"
                              icon="el-icon-top"
                              circle
                              plain
                              @click="shiftGroup(index, -1)"
                              v-show="index > 0"
                            ></el-button>
                          </el-tooltip>
                          <el-tooltip effect="dark" content="下移" placement="top" :enterable="false">
                            <el-button
                              type="primary"
                              size="mini"
                              icon="el-icon-bottom"
                              circle
                              plain
                              @click="shiftGroup(index, 1)"
                              v-show="index < editForm.configJson.length - 1"
                            ></el-button>
                          </el-tooltip>
                        </div>
                      </template>
                    </logic-content>
                  </el-tab-pane>
                </el-tabs>
              </template>
              <div class="no-group" v-else @click="addGroup(-1)"><i class="el-icon-plus"></i>添加枚举值</div>
            </div>
          </el-collapse-transition>

          <div class="section-title">
            <i
              :class="showResult ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
              @click="showResult = !showResult"
            ></i>
            结果预览
          </div>
          <el-collapse-transition>
            <div class="section-wrappper result-wrapper" v-if="showResult">
              <devired-result :previewResults="editForm.previewResults" title="枚举值"></devired-result>
            </div>
          </el-collapse-transition>
        </div>
      </el-form>
    </div>
    <logic-drawer ref="logicDrawer" :disabled="true" @confirm="handleSave"></logic-drawer>
  </div>
</template>

<script>
import factoryConfigList from '@/views/modules/factory/factory-config-list'
import logicContent from './logic-content'
import deviredResult from '../../components/devired-result'
import logicDrawer from './logic-drawer'
import logic from './logic.js'
import cloneDeep from 'lodash/cloneDeep'
export default {
  components: {
    factoryConfigList,
    logicContent,
    deviredResult,
    logicDrawer
  },
  data() {
    return {
      loading: false,
      showLogic: true,
      showResult: false,
      oldConfig: [],
      activeEnum: 'enum0',
      editForm: {
        tagId: '',
        groupId: '',
        tagNm: '',
        fieldNm: '',
        tagStory: '',
        valueType: '',
        execFrequency: '',
        execDtList: [],
        execWkList: [],
        execTm: '',
        defaultEnum: '',
        rerun: false,
        rerunTime: 1,
        configJson: [
          {
            enum: '',
            logicalOperation: 'and',
            tagList: []
          }
        ],
        previewResults: []
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$route.query.tagId) {
        this.editForm.tagId = this.$route.query.tagId
        this.getDetail()
      }
      if (this.$route.query.groupId) this.editForm.groupId = this.$route.query.groupId
    })
  },
  methods: {
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`der/derTagLogicalGroup/getLogicalGroup/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.tagNm = data.data.derTagInfo.tagNm
          this.editForm.fieldNm = data.data.derTagInfo.fieldNm
          this.editForm.tagStory = data.data.derTagInfo.tagStory
          this.editForm.valueType = data.data.derTagInfo.valueType
          this.editForm.execFrequency = data.data.derTagInfo.execFrequency
          this.editForm.execDtList = data.data.derTagInfo.execDtList || []
          this.editForm.execWkList = data.data.derTagInfo.execWkList || []
          this.editForm.execTm = data.data.derTagInfo.execTm || ''
          const config = JSON.parse(data.data.derTagInfo.configJson)
          this.editForm.defaultEnum = config.defaultEnum
          this.editForm.rerun = !!data.data.derTagInfo.rerun
          this.editForm.rerunTime = data.data.derTagInfo.rerunTime || 1
          this.editForm.configJson = logic.initLogic(config.configEnums, data.data.baseTags)
          this.editForm.previewResults = JSON.parse(data.data.derTagInfo.previewResults)
          this.oldConfig = cloneDeep(this.editForm)
          if (config.catalogClassId) this.$refs.factoryConfigList.changeCatalogClass(config.catalogClassId)
          this.showLogic = false
          this.showResult = true
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    addItem(item) {
      let params = {
        tagId: item.assetId,
        tagNm: item.assetNm,
        valueType: item.valueType.toString(),
        valueTypeCode: item.valueTypeCode,
        tagCode: item.assetCode,
        isDerLabel: item.isDerLabel,
        enums: item.enums,
        operationType: item.valueType.toString() === '3' ? '=' : '',
        operationValue: '',
        labTbl: item.labTbl,
        labFldMap: item.labFldMap,
        dictDatabaseType: item.dbVal
      }
      let config = this.editForm.configJson
      this.editForm.configJson[config.length - 1].tagList.push(params)
    },
    addGroup(index = -1) {
      const config = {
        enum: '',
        logicalOperation: 'and',
        tagList: []
      }
      if (index < 0) this.editForm.configJson.push(config)
      else this.editForm.configJson.splice(index + 1, 0, config)
      this.activeEnum = 'enum' + (index + 1)
    },
    deleteGroup(index) {
      this.editForm.configJson.splice(index, 1)
      this.activeEnum = 'enum' + (index === 0 ? index : index - 1)
    },
    shiftGroup(index, sign) {
      this.editForm.configJson[index] = this.editForm.configJson.splice(
        index + sign,
        1,
        this.editForm.configJson[index]
      )[0]
      this.activeEnum = 'enum' + (index + sign)
    },
    handlePreview() {
      let isEmpty = false
      let enums = new Set()
      this.editForm.configJson.forEach(item => {
        if (!item.tagList.length) isEmpty = true
        enums.add(item.enum)
      })
      if (isEmpty) {
        this.$message.info('逻辑配置不能为空！')
        return
      }
      if (enums.size !== this.editForm.configJson.length) {
        this.$message.info('枚举值名称不能重复！')
        return
      }
      this.$refs.editForm.validate((valid, validResult) => {
        if (valid) {
          const config = {
            defaultEnum: this.editForm.defaultEnum,
            configEnums: logic.initParams(this.editForm.configJson)
          }
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('der/derTagLogicalGroup/previewResult'),
            method: 'post',
            data: this.$ajax.setData({
              configJson: JSON.stringify(config)
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.editForm.previewResults = data.data
              this.oldConfig = cloneDeep(this.editForm)
              this.showLogic = false
              this.showResult = true
              this.$message.success(data.msg)
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        } else {
          const index = Object.keys(validResult)[0].substring(11, 12)
          this.activeEnum = 'enum' + index
        }
      })
    },
    submit() {
      if (!this.$utils.compareObject(this.oldConfig, this.editForm)) {
        this.$message.info('逻辑配置有变化，请先预览再保存！')
        return
      }
      let enums = new Set()
      this.editForm.configJson.forEach(item => enums.add(item.enum))
      if (enums.size !== this.editForm.configJson.length) {
        this.$message.info('枚举值名称不能重复！')
        return
      }
      this.$refs.editForm.validate((valid, validResult) => {
        if (valid) {
          let params = {
            tagId: this.editForm.tagId,
            tagNm: this.editForm.tagNm,
            fieldNm: this.editForm.fieldNm,
            tagStory: this.editForm.tagStory,
            valueType: 1,
            rerun: this.editForm.rerun,
            rerunTime: this.editForm.rerunTime,
            execFrequency: this.editForm.execFrequency,
            execDtList: this.editForm.execDtList,
            execWkList: this.editForm.execWkList,
            execTm: this.editForm.execTm
          }
          this.$refs.logicDrawer.showDrawer(params)
        } else {
          const index = Object.keys(validResult)[0].substring(11, 12)
          this.activeEnum = 'enum' + index
        }
      })
    },
    handleSave(params) {
      this.editForm.execFrequency = params.execFrequency
      this.editForm.execDtList = params.execDtList
      this.editForm.execWkList = params.execWkList
      this.editForm.execTm = params.execTm
      this.editForm.fieldNm = params.fieldNm
      this.editForm.tagNm = params.tagNm
      this.editForm.tagStory = params.tagStory
      this.editForm.valueType = params.valueType
      this.editForm.rerun = params.rerun
      this.editForm.rerunTime = params.rerunTime
      const configJson = {
        defaultEnum: this.editForm.defaultEnum,
        configEnums: logic.initParams(this.editForm.configJson),
        catalogClassId: this.$refs.factoryConfigList.getCatalogClass()
      }
      let config = {
        configJson: JSON.stringify(configJson),
        execFrequency: params.execFrequency,
        execDtList: params.execDtList,
        execWkList: params.execWkList,
        execTm: params.execTm,
        fieldNm: params.fieldNm,
        previewResults: JSON.stringify(this.editForm.previewResults),
        tagNm: params.tagNm,
        tagStory: params.tagStory,
        valueType: params.valueType,
        rerun: params.rerun,
        rerunTime: params.rerunTime
      }
      if (this.editForm.tagId) config.tagId = this.editForm.tagId
      if (this.editForm.groupId) config.groupId = this.editForm.groupId
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('der/derTagLogicalGroup/saveLogicalGroup'),
        method: 'post',
        data: this.$ajax.setData(config)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (!this.editForm.tagId) this.editForm.tagId = data.data
          this.$message.success(data.msg)
          this.$refs.logicDrawer.beforeClose()
          this.oldConfig = cloneDeep(this.editForm)
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    clearConfig() {
      this.editForm.defaultEnum = ''
      this.editForm.configJson = [
        {
          enum: '',
          logicalOperation: 'and',
          tagList: []
        }
      ]
      this.editForm.previewResults = []
      this.showLogic = true
    },
    clear() {
      this.$confirm('确定取消最新的编辑？').then(() => {
        const config = cloneDeep(this.oldConfig)
        if (config.tagId) {
          this.editForm.defaultEnum = config.defaultEnum
          this.editForm.tagNm = config.tagNm
          this.editForm.fieldNm = config.fieldNm
          this.editForm.tagStory = config.tagStory
          this.editForm.valueType = config.valueType
          this.editForm.execFrequency = config.execFrequency
          this.editForm.execDtList = config.execDtList
          this.editForm.execWkList = config.execWkList
          this.editForm.execTm = config.execTm
          this.editForm.configJson = config.configJson
          this.editForm.previewResults = config.previewResults
          this.editForm.rerun = config.rerun
          this.editForm.rerunTime = config.rerunTime
        } else {
          this.editForm.defaultEnum = ''
          this.editForm.tagNm = ''
          this.editForm.fieldNm = ''
          this.editForm.tagStory = ''
          this.editForm.valueType = ''
          this.editForm.rerun = false
          this.editForm.rerunTime = 1
          this.editForm.execFrequency = ''
          this.editForm.execDtList = []
          this.editForm.execWkList = []
          this.editForm.execTm = ''
          this.editForm.configJson = [
            {
              enum: '',
              logicalOperation: 'and',
              tagList: []
            }
          ]
          this.editForm.previewResults = []
        }
        this.$forceUpdate()
      })
    }
  }
}
</script>

<style lang="scss">
.devired-logic {
  .factory-top {
    line-height: 50px;
    color: $theme-color;
    svg {
      margin-right: 10px;
    }
  }
  .factory-content-wrapper {
    height: calc(100% - 60px);
    overflow-y: auto;
  }
  .section-title {
    font-size: 18px;
    font-weight: bold;
    height: 80px;
    padding: 20px;
    line-height: 40px;
    color: #1e3592;
    background-color: #c0d2f6;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    & + .section-title {
      margin-top: 10px;
    }
    i {
      cursor: pointer;
    }
    span {
      font-size: 14px;
      font-weight: normal;
      color: #4a5593;
      margin-left: 10px;
    }
  }
  .section-wrappper {
    margin-bottom: 10px;
  }
  .result-wrapper {
    border: 1px solid #e4e7ed;
  }
  .el-tabs__item {
    font-size: 15px;
    font-weight: bold;
  }
  .default-enum {
    padding: 10px 20px 5px 20px;
    margin-bottom: 10px;
    border: 1px solid #e4e7ed;
    box-shadow: 1px 2px 5px #e4e7ed;
    .el-form-item__label {
      font-size: 17px;
      color: $theme-color;
    }
    .el-input__icon {
      font-size: 17px;
      color: $theme-color;
    }
    .el-input__inner {
      font-size: 17px;
      padding-left: 40px;
      border: 0;
    }
  }
  .no-group {
    padding: 20px;
    margin: 10px 0;
    border: 1px solid $border-color;
    background-color: #f6f7f8;
    text-align: center;
    cursor: pointer;
    i {
      margin-right: 10px;
    }
  }
  .el-tabs {
    margin-bottom: 10px;
  }
}
</style>
